package com.meiyuetao.myt.sale.web.action;

import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;

import lab.s2jh.core.annotation.MetaData;
import lab.s2jh.core.pagination.GroupPropertyFilter;
import lab.s2jh.core.pagination.PropertyFilter;
import lab.s2jh.core.pagination.PropertyFilter.MatchType;
import lab.s2jh.core.security.AclService;
import lab.s2jh.core.service.BaseService;
import lab.s2jh.core.service.Validation;
import lab.s2jh.core.web.view.OperationResult;

import org.apache.commons.lang3.StringUtils;
import org.apache.struts2.rest.HttpHeaders;
import org.springframework.beans.factory.annotation.Autowired;

import com.meiyuetao.myt.core.constant.BizDataDictCategoryEnum;
import com.meiyuetao.myt.core.web.MytBaseController;
import com.meiyuetao.myt.finance.entity.PayNotifyHistory;
import com.meiyuetao.myt.finance.entity.PayNotifyHistory.ProcessStatusEnum;
import com.meiyuetao.myt.finance.service.PayNotifyHistoryService;
import com.meiyuetao.myt.sale.entity.BoxOrder;
import com.meiyuetao.myt.sale.entity.BoxOrder.BoxOrderStatusEnum;
import com.meiyuetao.myt.sale.entity.BoxOrderDetail;
import com.meiyuetao.myt.sale.service.BoxOrderDetailService;
import com.meiyuetao.myt.sale.service.BoxOrderService;

@MetaData("BoxOrderController")
public class BoxOrderController extends MytBaseController<BoxOrder, Long> {

    @Autowired
    private BoxOrderService boxOrderService;

    @Autowired
    private PayNotifyHistoryService payNotifyHistoryService;
    @Autowired
    private BoxOrderDetailService boxOrderDetailService;
    @Autowired
    private AclService aclService;

    private String[] orderSid;

    public String[] getOrderSid() {
        return orderSid;
    }

    public void setOrderSid(String[] orderSid) {
        this.orderSid = orderSid;
    }

    @Override
    protected BaseService<BoxOrder, Long> getEntityService() {
        return boxOrderService;
    }

    public HttpHeaders kjPost() {
        String msg = boxOrderService.kjPost(getOrderSid());
        setModel(OperationResult.buildSuccessResult(msg));
        return buildDefaultHttpHeaders();
    }

    @Override
    protected void setupDetachedBindingEntity(Long id) {
        bindingEntity = getEntityService().findDetachedOne(id, "boxOrderDetails", "boxOrderDetailCommodities", "scores", "customerAccountHists", "vipScoreHistories",
                "vipBakMoneyHistories");
    }

    @Override
    protected void checkEntityAclPermission(BoxOrder entity) {
        // 限定只能访问登录用户所在商家的数据
        /*
         * String aclCodePrefix = aclService.getLogonUserAclCodePrefix();
         * Partner agentPartner = entity.getAgentPartner(); if (agentPartner !=
         * null && StringUtils.isNotBlank(aclCodePrefix)) { String
         * agentPartnerCode = agentPartner.getCode(); if
         * (!agentPartnerCode.startsWith(aclCodePrefix)) { throw new
         * DataAccessDeniedException(); } }
         */
    }

    @Override
    protected void appendFilterProperty(GroupPropertyFilter groupPropertyFilter) {
        // 限定只能访问登录用户所在商家的数据
        /*
         * String aclCodePrefix = aclService.getLogonUserAclCodePrefix(); if
         * (StringUtils.isNotBlank(aclCodePrefix)) {
         * groupPropertyFilter.forceAnd(new PropertyFilter(MatchType.BW,
         * "agentPartner.code", aclCodePrefix)); }
         */
    }

    @Override
    @MetaData("保存")
    public HttpHeaders doSave() {
        return super.doSave();
    }

    @MetaData("订单改价")
    public HttpHeaders modifyPrice() {
        boxOrderService.modifyPrice(bindingEntity);
        setModel(OperationResult.buildSuccessResult("订单改价成功"));
        return buildDefaultHttpHeaders();
    }

    @Override
    @MetaData("删除")
    public HttpHeaders doDelete() {
        return super.doDelete();
    }

    @Override
    @MetaData("查询")
    public HttpHeaders findByPage() {
        return super.findByPage();
    }

    @MetaData(value = "订单行项列表")
    public HttpHeaders boxOrderDetails() {
        List<BoxOrderDetail> boxOrderDetails = bindingEntity.getBoxOrderDetails();
        setModel(buildPageResultFromList(boxOrderDetails));
        return buildDefaultHttpHeaders();
    }

    @MetaData(value = "财务支付类型")
    public HttpHeaders payMode() {
        Map<String, String> map = getPayModeMap();
        setModel(map);
        return buildDefaultHttpHeaders();
    }

    @MetaData(value = "订单付款历史记录")
    public HttpHeaders findPayHistory() {
        Set<PayNotifyHistory> payHistorySet = new HashSet<PayNotifyHistory>();
        GroupPropertyFilter groupPropertyFilter = GroupPropertyFilter.buildDefaultAndGroupFilter();
        if (StringUtils.isNotBlank(bindingEntity.getCautionOutTradeNo())) {
            groupPropertyFilter.append(new PropertyFilter(MatchType.EQ, "outTradeNo", bindingEntity.getCautionOutTradeNo()));
            groupPropertyFilter.append(new PropertyFilter(MatchType.EQ, "processStatus", ProcessStatusEnum.OK));
            List<PayNotifyHistory> payNotifyHistoryList1 = payNotifyHistoryService.findByFilters(groupPropertyFilter);
            payHistorySet.addAll(payNotifyHistoryList1);
        }
        if (StringUtils.isNotBlank(bindingEntity.getPayVoucher())) {
            groupPropertyFilter = GroupPropertyFilter.buildDefaultAndGroupFilter();
            groupPropertyFilter.append(new PropertyFilter(MatchType.EQ, "tradeNo", bindingEntity.getPayVoucher()));
            groupPropertyFilter.append(new PropertyFilter(MatchType.EQ, "processStatus", ProcessStatusEnum.OK));
            List<PayNotifyHistory> payNotifyHistoryList2 = payNotifyHistoryService.findByFilters(groupPropertyFilter);
            payHistorySet.addAll(payNotifyHistoryList2);
        }
        for (BoxOrderDetail boxOrderDetail : bindingEntity.getBoxOrderDetails()) {
            if (StringUtils.isNotBlank(boxOrderDetail.getPayVoucher())) {
                groupPropertyFilter = GroupPropertyFilter.buildDefaultAndGroupFilter();
                groupPropertyFilter.append(new PropertyFilter(MatchType.EQ, "tradeNo", boxOrderDetail.getPayVoucher()));
                groupPropertyFilter.append(new PropertyFilter(MatchType.EQ, "processStatus", ProcessStatusEnum.OK));
                List<PayNotifyHistory> payNotifyHistoryList3 = payNotifyHistoryService.findByFilters(groupPropertyFilter);
                payHistorySet.addAll(payNotifyHistoryList3);
            }
        }
        setModel(buildPageResultFromList(new ArrayList<PayNotifyHistory>(payHistorySet)));
        return buildDefaultHttpHeaders();
    }

    public Map<String, String> getPayModeMap() {
        return this.findMapDataByDataDictPrimaryKey(BizDataDictCategoryEnum.IYOUBOX_FINANCE_PAY_MODE.name());
    }

    public Map<String, String> getPaperModeMap() {
        return this.findMapDataByDataDictPrimaryKey(BizDataDictCategoryEnum.IYOUBOX_GIFT_PAPER_MODE.name());
    }

    public Map<String, String> getTradeTypeMap() {
        return this.findMapDataByDataDictPrimaryKey(BizDataDictCategoryEnum.IYOUBOX_TRADE_TYPE.name());
    }

    @MetaData("订单取消操作")
    public HttpHeaders cancelOrder() {
        // 已付款不能取消
        Boolean flag = false;
        for (BoxOrderDetail boxOrderDetail : bindingEntity.getBoxOrderDetails()) {
            if (boxOrderDetail.getPayTime() != null) {
                flag = true;
                break;
            }
        }
        Validation.isTrue(!flag, "已付款不能取消");
        boxOrderService.cancelOrder(bindingEntity);
        setModel(OperationResult.buildSuccessResult("订单已取消"));
        return buildDefaultHttpHeaders();
    }

    @MetaData("订单收货完成操作")
    public HttpHeaders recvConfirm() {
        boxOrderService.recvConfirm(bindingEntity);
        setModel(OperationResult.buildSuccessResult("订单收货完成"));
        return buildDefaultHttpHeaders();
    }

    @MetaData("订单发货完成操作")
    public HttpHeaders doDelivery() {
        boxOrderService.deliverySave(bindingEntity);
        setModel(OperationResult.buildSuccessResult("订单发货完成"));
        return buildDefaultHttpHeaders();
    }

    @MetaData("订单完结操作")
    public HttpHeaders successClose() {
        // Validation.isTrue(bindingEntity.getDeliveryFinishTime() != null,
        // "订单还未完成收货");
        boxOrderService.successClose(bindingEntity);
        setModel(OperationResult.buildSuccessResult("订单完结成功"));
        return buildDefaultHttpHeaders();
    }

    /**
     * 免单（用户已下单 用户已付款）
     * 
     * @return
     * @since 2015/4/21
     * @author harvey
     */
    @MetaData("免单操作")
    public HttpHeaders free() {
        // 仅当用户已下单的状态才可以进行免单操作
        BoxOrderStatusEnum bsEnum = BoxOrderStatusEnum.S10O;
        if (bsEnum.equals(bindingEntity.getOrderStatus())) {
            bindingEntity.setOrderStatus(BoxOrderStatusEnum.S20PYD);
            boxOrderService.free(bindingEntity);
            setModel(OperationResult.buildSuccessResult("免单成功"));
        } else {
            setModel(OperationResult.buildSuccessResult("订单状态不是[用户已下单]状态，取消免单操作失败"));
        }
        return buildDefaultHttpHeaders();
    }

    /**
     * 取消免单（用户已付款 用户已下单）
     * 
     * @return
     * @since 2015/4/21
     * @author harvey
     */
    @MetaData("取消免单操作")
    public HttpHeaders freeCancle() {
        // 仅当用户已付款状态时才可以进行取消免单操作
        BoxOrderStatusEnum bsEnum = BoxOrderStatusEnum.S20PYD;
        if (bsEnum.equals(bindingEntity.getOrderStatus())) {
            bindingEntity.setOrderStatus(BoxOrderStatusEnum.S10O);
            boxOrderService.freeCancle(bindingEntity);
            setModel(OperationResult.buildSuccessResult("取消免单成功"));
        } else {
            setModel(OperationResult.buildSuccessResult("订单状态不是[用户已付款]状态，取消免单操作失败"));
        }
        return buildDefaultHttpHeaders();
    }

    @MetaData("订单退款操作")
    public HttpHeaders backCommodity() {
        Validation.isTrue(BoxOrderStatusEnum.S70CLS.equals(bindingEntity.getOrderStatus()), "不是完结订单！");
        boxOrderService.backCommodity(bindingEntity);
        setModel(OperationResult.buildSuccessResult("订单退款成功"));
        return buildDefaultHttpHeaders();
    }

}